#include<iostream>
#include<cstdlib>
#include<cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>

using namespace std;

void usage(string proc)
{
    cout << "Usage:\n\t" << proc << " local_port\n" << endl;
}
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(1);
    }
    //端口号
    uint16_t port=stoi(argv[2]);
    string ip=argv[1];

    //同样的也要创建socket
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        cerr<<"socket error!"<<endl;
    }
     // 2. client也是要bind，一定要，client也要有自己的IP和PORT。不要显式[和server一样用bind函数]
    // a. udp client首次发送数据的时候，OS会自己自动随机的给client进行bind --- 防止client port冲突。要bind，必然要和port关联！
    // b. bind时候——首次发送数据的时候
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    //初始化
    server.sin_family=AF_INET;
    server.sin_port=htons(port);
    server.sin_addr.s_addr=inet_addr(ip.c_str());

    string message;
    //通信
    while(1)
    {
        cout<<"Place Enter:"<<endl;
        getline(cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(sockaddr*)&server,sizeof(server));

        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }


    // 构建目标主机的socket信息
    return 0;
}